﻿<%@ Page Title="Sales Quotation" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="SalesQuotation.aspx.cs" Inherits="SapB1WebPOS.SalesQuotation" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<style>
    #grid
{
    border-width:0;
    height:100%;
}
</style>
    <script type="text/javascript">
        var docDatePicker, docDueDatePicker, taxDateDatePicker;
        var oItem = {};
        var oWarehouse = {};
        var oVatGroup = {};
        var oDocLine = {};
        var oDocHeader = {};
        var isInsert = "1";
        var gird;
        var docEntry = 0;
        var isUpdate = false;
        var docStatus;
        var editRowIndex;
        var currentPage = "SalesQuotation.aspx";
        function LoadBP() {
            var cardCode = $("#CardCode").val();
            $.ajax({
                type: "POST",
                url: "SalesOrder.aspx/GetBPByCardCode",
                data: JSON.stringify({
                    cardCode: cardCode
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result.length > 0) {
                            $("#CardName").val(result[0].CardName)
                            setEnabledAddNewItemButton(true);
                        }
                        else {
                            ajaxindicatorstop();
                            OpenCustomerList();
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function CreateNew() {
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                },
                failure: function (response) {
                },
                error: function (response) {
                }
            });
            location.href = "SalesQuotation.aspx?DocEntry=0&IsUpdate=false";
        }
        function CopyToSO() {
            var docEntry = $("#DocEntry").val();
            location.href = "SalesOrder.aspx?SQDocEntry=" + docEntry + "&DocEntry=0&IsUpdate=false";
        }
        function OpenCustomerList() {
            var wnd = $("#customerList")
                        .kendoWindow({
                            title: "List of Business Partners",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 800,
                            height: 500,
                            content: { type: "POST", url: "BusinessPartnersList.aspx?CardType=C", data: {} },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
            wnd.bind('close', function () {
                $("#customerList").empty();
            });
        }
        function OpenItemList() {
            var wnd = $("#itemList")
                        .kendoWindow({
                            title: "List of Item Master Data",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1100,
                            height: 500,
                            content: { type: "POST", url: "ItemMasterDataList.aspx", data: {} },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
            wnd.bind('close', function () {
                $("#itemList").empty();
            });
        }
        function OpenSQList() {
            var wnd = $("#salesQuotationList")
                        .kendoWindow({
                            title: "List of Sales Quotations",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1200,
                            height: 500,
                            content: { type: "POST", url: "SalesQuotationList.aspx", data: {} },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
            wnd.bind('close', function () {
                $("#salesQuotationList").empty();
            });
        }
        function setEnabledAddNewItemButton(enabled) {
            if (enabled) {
                $(".k-add-button").removeClass("k-state-disabled").addClass("k-grid-add");
            }
            else {
                $(".k-add-button").addClass("k-state-disabled").removeClass("k-grid-add");
            }
        }
        function ChooseCustomer(customerID, customerName) {
            selectedCustomerID = customerID;
            $("#CardCode").val(customerID)
            $("#CardName").val(customerName)
            $("#customerList").empty();
            if ($("#customerList").data("kendoWindow") != null) {
                $("#customerList").data("kendoWindow").close();
            }
            setEnabledAddNewItemButton(true);
        }
        function ChooseSQ(header) {
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    grid.dataSource.data([]);
                    LoadHeader(header);
                    docEntry = header.DocEntry;
                    grid.dataSource.read();
                    var url = "SalesQuotation.aspx?DocEntry=" + docEntry + "&IsUpdate=true"
                    history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);
                },
                failure: function (response) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            $("#salesQuotationList").data("kendoWindow").close();
            $("#salesQuotationList").empty();
        }
        function lineTotalTextBox(container, options) {
            $('<span name ="LineTotal" id ="LineTotal"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function priceAftetDiscountTextBox(container, options) {
            $('<span name ="Price" id ="Price"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function totalTextBox(container, options) {
            $('<span name ="Total" id ="Total"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function priceBeforeDiscountTextBox(container, options) {
            $('<span name ="TotalBefDisc" id ="TotalBefDisc"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function uoMTextBox(container, options) {
            $('<span name ="unitMsr" id ="unitMsr"  data-bind="text:' + options.field + '"></span>').appendTo(container);
        }
        function warehousekendoComboBox(container, options) {
            $('<input    data-text-field="WhsName" data-value-field="WhsCode" Name="WhsCode" ID="WhsCode" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            filter: "contains",
                            placeholder: "[Select Warehouse]",
                            suggest: true,
                            dataSource: oWarehouse
                        });
            //            $('<span class="k-invalid-msg" data-for="WhsCode" style="width:600px;"></span>').appendTo(container);
        }
        function vatkendoComboBox(container, options) {
            $('<input   data-text-field="Name" data-value-field="Code" Name="VatGroup" ID="VatGroup" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            filter: "contains",
                            placeholder: "[Select VAT]",
                            suggest: true,
                            dataSource: oVatGroup,
                            change: function (e) {
                                var cmb = this;
                                if (cmb.selectedIndex < 0) {
                                    cmb.value(null);
                                }
                                else {
                                    var changedCode = this.value();
                                    var vatPrcnt = 0;
                                    $.each(oVatGroup, function (i, o) {
                                        if (o.Code == changedCode) {
                                            vatPrcnt = o.Rate;
                                        }
                                    });
                                    var rowData = $('#grid').data().kendoGrid.dataSource.data()[editRowIndex];
                                    rowData.set('VatPrcnt', vatPrcnt)
                                    UpdateRow(rowData);
                                    UpdateTotal();
                                }
                            }
                        });
            //            $('<span class="k-invalid-msg" data-for="VatGroup"  style="width:200px;"></span>').appendTo(container);
        }
        function itemTextBox(container, options) {
            $('<input disabled style="width:80%;" name="ItemCode" id="ItemCode" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
            $('<span class="k-icon k-i-search" style="margin-left:8px;width:16px; cursor: pointer;" onclick="OpenItemList()"  title="Choose item" ></span>').appendTo(container);
        }
        function itemkendoComboBox(container, options) {
            $('<input disabled style="width:90%;" name="Dscription" id="Dscription" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
            $('<span class="k-icon k-i-search" style="margin-left:8px;width:16px;cursor: pointer;" onclick="OpenItemList()"  title="Choose item" ></span>').appendTo(container);
        }
        function ChooseItem(itemCode, itemName, basePrice, uom, vatGourpSa, vatGourpPu, whsCode) {
            var rowData = $('#grid').data().kendoGrid.dataSource.data()[editRowIndex];
            // Get Price
            var cardCode = $("#CardCode").val();
            var docDate = $("#docDate").val();
            rowData.set('ItemCode', itemCode);
            rowData.set('Dscription', itemName)

            rowData.set('unitMsr', uom);
            rowData.set('VatGroup', vatGourpSa);
            $.ajax({
                type: "POST",
                url: currentPage + "/GetSAPItemPrice",
                data: JSON.stringify({
                    cardCode: cardCode,
                    itemCode: itemCode,
                    amount: rowData.Quantity,
                    refDate: docDate
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {

                        basePrice = response.d;
                        rowData.set('PriceBefDi', basePrice);
                        var vatPrcnt = 0;
                        var vatGroupName;
                        $.each(oVatGroup, function (i, o) {
                            if (o.Code == vatGourpSa) {
                                vatPrcnt = o.Rate;
                                vatGroupName = o.Name;
                            }
                        });
                        rowData.set('VatGroupName', vatGroupName);
                        rowData.set('VatPrcnt', vatPrcnt)
                        if ($('#VatGroup').data("kendoDropDownList") != null) {
                            $('#VatGroup').data("kendoDropDownList").value(vatGourpSa);
                        }
                        var whsName;
                        $.each(oWarehouse, function (i, o) {
                            if (o.WhsCode == whsCode) {
                                whsName = o.WhsName;
                            }
                        });
                        rowData.set('WhsCode', whsCode);
                        rowData.set('WhsName', whsName)
                        if ($('#WhsCode').data("kendoDropDownList") != null) {
                            $('#WhsCode').data("kendoDropDownList").value(whsCode);
                        }
                        UpdateRow(rowData);
                        UpdateTotal();
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            if ($("#itemList").data("kendoWindow") != null) {
                $("#itemList").data("kendoWindow").close();
                $("#itemList").empty();
            }
        }
        function UpdateRow(rowData) {
            var discountAmt = 0;
            var priceAfterDiscount = 0;
            var totalAfterDiscount = 0;
            var vatSum = 0;
            var totalBeforeDiscount = 0;
            var vatPrcnt = 0, discount = 0, unitPrice = 0, quantity = 0, total = 0;

            vatPrcnt = rowData.VatPrcnt;
            discount = rowData.DiscPrcnt;
            unitPrice = rowData.PriceBefDi;
            quantity = rowData.Quantity;

            priceAfterDiscount = unitPrice * (100 - discount) / 100;
            totalBeforeDiscount = unitPrice * quantity;
            totalAfterDiscount = priceAfterDiscount * quantity;

            vatSum = (totalAfterDiscount * vatPrcnt) / 100;
            total = totalAfterDiscount + vatSum;

            rowData.set('Price', priceAfterDiscount);
            rowData.set('VatSum', vatSum);
            rowData.set('LineTotal', totalAfterDiscount);
            rowData.set('TotalBefDisc', totalBeforeDiscount);
            rowData.set('Total', total);
        }
        function GetWarehouses() {
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/GetWareHouses",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oWarehouse = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function GetTaxs() {
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/GetTaxs",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oVatGroup = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function resizeGrid() {
            var gridElement = $("#grid"),
        dataArea = gridElement.find(".k-grid-content"),
        gridHeight = gridElement.innerHeight(),
        otherElements = gridElement.children().not(".k-grid-content"),
        otherElementsHeight = 0;
            otherElements.each(function () {
                otherElementsHeight += $(this).outerHeight();
            });
            dataArea.height(gridHeight - otherElementsHeight);
            gridElement.height($(document).height() - 340);
        }

        $(window).resize(function () {
            setTimeout(function () { resizeGrid(); }, 0); 
        });
        $(document).ready(function () {

            docDatePicker = $("#docDate").kendoDatePicker({
                value: new Date(),
                required: true
            }).data("kendoDateTimePicker");
            docDueDatePicker = $("#docDueDate").kendoDatePicker({
                value: new Date(),
                required: true
            }).data("kendoDatePicker");
            taxDateDatePicker = $("#taxDate").kendoDatePicker({
                value: new Date(),
                required: true
            }).data("kendoDatePicker");

            isUpdate = '<%= Request.QueryString["IsUpdate"] %>';
            if (isUpdate == 'false') {
                isUpdate = false;
            }
            if (isUpdate == 'true') {
                isUpdate = true;
            }
            $('#DocEntry').val('<%= Request.QueryString["DocEntry"] %>');
            docEntry = $('#DocEntry').val();

            GetWarehouses();
            GetTaxs();

            if (docEntry != null && docEntry != '0') {
                GetHeaderByDocEntry();
            }
            else {
                $('#btnCopyTo').attr('disabled', 'disabled');
                $('#btnCopyTo').addClass("k-button k-state-disabled");

            }

            //Clear Session
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    //Load Grid
                    grid = $("#grid").kendoGrid({
                        dataSource: {
                            transport: {
                                read: {
                                    type: "GET",
                                    url: "SalesQuotation.aspx/GetDocLines",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    complete: function (jqXHR, textStatus) {
                                        if ($('#CardCode').val() != '') {
                                            setEnabledAddNewItemButton(true);
                                        }
                                        else {
                                            setEnabledAddNewItemButton(false);
                                        }
                                        UpdateTotal();
                                    }
                                },
                                destroy: {
                                    type: "GET",
                                    url: "SalesQuotation.aspx/DeleteDocLine",
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    complete: function (jqXHR, textStatus) {
                                        UpdateTotal();
                                    }
                                },
                                parameterMap: function (data, operation) {
                                    if (operation === "read") {
                                        return { docEntry: docEntry };
                                    }
                                    if (operation === "destroy") {
                                        return { lineNum: data.LineNum };
                                    }
                                },
                                serverPaging: true,
                                serverSorting: true,
                                serverFiltering: true
                            },
                            type: "odata", //Important!!!!
                            schema: {
                                data: function (a) {
                                    if (a.d != null) {
                                        var data = a.d.Data;
                                        return data;
                                    }
                                },
                                total: "d.Count",
                                model: {
                                    id: "LineNum",
                                    fields: {
                                        DocEntry: { type: "string" },
                                        LineNum: { type: "string" },
                                        Dscription: { type: "string" },
                                        ItemCode: { type: "string" },
                                        WhsCode: { type: "string" },
                                        WhsName: { type: "string" },
                                        VatGroup: { type: "string" },
                                        VatGroupCode: { type: "string" },
                                        VatGroupName: { type: "string" },
                                        unitMsr: { type: "string" },
                                        Quantity: { type: "number" },
                                        VatPrcnt: { type: "number" },
                                        PriceBefDi: { type: "number" },
                                        Price: { type: "number" },
                                        DiscPrcnt: { type: "number" },
                                        LineTotal: { type: "number" },
                                        LineStatus: { type: "LineStatus" },
                                        DocStatus: { type: "LineStatus" },
                                        TotalBefDisc: { type: "number" }
                                    }
                                }
                            }
                        },
                        sortable: true,
                        resizable: true,
                        height: $(document).height() - 340,
                        selectable: "row",
                        toolbar: [{ name: 'create', text: 'Add New Item' }, { name: 'excel'}],
                        excel: {
                            fileName: "Sales Quotation Line.xlsx",
                            filterable: true
                        },
                        batch: true,
                        columns: [
                         { command: ["edit", "destroy"], title: "Action", width: "260px" },
                            { field: "DocEntry", title: "DocEntry", width: 100, hidden: true },
                            { field: "LineNum", title: "LineNum", width: 150, hidden: true },
                            { field: "LineStatus", title: "LineNum", width: 150, hidden: true },
                            { field: "VatPrcnt", title: "VatPrcnt", width: 150, hidden: true },
                            { field: "VatSum", title: "VatSum", width: 150, hidden: true },
                            { field: "ItemCode", title: "Item Code", width: 200, editor: itemTextBox },
                            { field: "Dscription", title: "Item Name", width: 400, editor: itemkendoComboBox },
                            { field: "unitMsr", title: "UoM", width: 100, editor: uoMTextBox },
                            { field: "Quantity", title: "Quantity", width: 120, attributes: { style: "text-align:right;"} },
                            { field: "PriceBefDi", title: "Price", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;"} },
                            { field: "TotalBefDisc", title: "Total Before Discount", hidden: true, width: 180, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: priceBeforeDiscountTextBox },
                            { field: "DiscPrcnt", title: "Discount (%)", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;"} },
                            { field: "Price", title: "Price After Discount", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: priceAftetDiscountTextBox },
                            { field: "LineTotal", title: "Total After Discount ", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: lineTotalTextBox },
                            { field: "WhsCode", title: "Warehouse", width: 220, editor: warehousekendoComboBox, template: "#=WhsName#" },
                            { field: "VatGroup", title: "VAT", width: 200, editor: vatkendoComboBox, template: "#=VatGroupName#" },
                            { field: "Total", title: "Total", width: 150, format: "{0:n}", type: "number", attributes: { style: "text-align:right;" }, editor: totalTextBox }
                            ],
                        editable: {
                            mode: "inline",
                            confirmation: "Are you sure you want to remove this item?",
                            createAt: "bottom"
                        },
                        edit: function (e) {
                            $('[name="DocEntry"]').attr("disabled", true);
                            $('[name="LineNum"]').attr("disabled", true);
                            $('[name="LineTotal"]').attr("disabled", true);
                            if (e.model.isNew()) {
                                $("a.k-grid-update")[0].innerHTML = "<span class='k-icon k-update'></span>Save";
                                isInsert = "1";
                                e.container
                             .find("input[name=DocEntry]") // get the input element for the field
                             .val($("#DocEntry").val()) // set the value
                             .change(); // trigger change in order to notify the model binding
                                e.model.set("Quantity", 1);
                                var rowsCount = grid.dataSource.total();
                                editRowIndex = rowsCount - 1;
                                OpenItemList();
                            }
                            else {
                                isInsert = "2";
                            }

                        },
                        cancel: function (e) {
                            UpdateTotal();
                        },
                        save: function (e) {
                            var listTextBox = $("input:text");
                            for (var i = 0; i < listTextBox.length; i++) {
                                var name = listTextBox[i].name;
                                if (name.length > 0) {
                                    oDocLine[name] = $("[name=" + name + "]").val();
                                }
                            }

                            oDocLine.WhsCode = $('#WhsCode').data("kendoDropDownList").value();
                            oDocLine.WhsName = $('#WhsCode').data("kendoDropDownList").text();
                            oDocLine.VatGroup = $('#VatGroup').data("kendoDropDownList").value();
                            oDocLine.VatGroupName = $('#VatGroup').data("kendoDropDownList").text();
                            oDocLine.unitMsr = $('#unitMsr').text();
                            oDocLine.TotalBefDisc = $('#TotalBefDisc').text();
                            oDocLine.LineTotal = $('#LineTotal').text();
                            oDocLine.Total = $('#Total').text();
                            oDocLine.Price = $('#Price').text();
                            //Update or Insert Item
                            $.ajax({
                                type: "POST",
                                url: "SalesQuotation.aspx/UpdateDoc",
                                data: JSON.stringify({
                                    oDocLine: JSON.stringify(oDocLine),
                                    isInsert: isInsert,
                                    rowIndex: 1
                                }),
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (data) {
                                    grid.dataSource.read();
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    if (jqXHR.status == 500) {
                                        alert('Internal error: ' + jqXHR.responseText);
                                    } else {
                                        alert('Unexpected error.' + jqXHR.responseText);
                                    }
                                }
                            });
                        },
                        dataBound: onDataBound
                    }).data("kendoGrid");

                    $(".k-grid-add").addClass("k-add-button");
                },
                failure: function (response) {
                },
                error: function (response) {
                }
            });

        });
        function onDataBound(e) {
            var grid = $("#grid").data("kendoGrid");

            $(grid.tbody).on("click", "td", function (e) {
                var row = $(this).closest("tr");
                editRowIndex = $("tr", grid.tbody).index(row);
                var colIdx = $("td", row).index(this);
            });

            var docStatusOfLine = $('#DocStatus').val();
            //Selects all edit buttons
            $("#grid tbody tr .k-grid-edit").each(function () {
                var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
                //Check in the current dataItem if the row is editable
                if (currentDataItem.LineStatus == 'C') {
                    $(this).remove();
                }
            });

            //Selects all delete buttons
            $("#grid tbody tr .k-grid-delete").each(function () {
                var currentDataItem = $("#grid").data("kendoGrid").dataItem($(this).closest("tr"));
                //Check in the current dataItem if the row is deletable
                if (currentDataItem.LineStatus == 'C') {
                    $(this).remove();
                }
            });
            if (docStatusOfLine == 'Closed' || docStatusOfLine == 'Canceled') {
                $("#grid .k-add").parent().hide();
                $("#grid").data("kendoGrid").hideColumn(0);
            }
            else {
                $("#grid .k-add").parent().show();
                $("#grid").data("kendoGrid").showColumn(0);
            }
            $(grid.tbody).on("blur", "td", function (e) {
                var row = $(this).closest("tr");
                var rowIdx = $("tr", grid.tbody).index(row);
                var colIdx = $("td", row).index(this);
                var colName = $('#grid').find('th').eq(colIdx).text();
                var columnField = $('#grid').find("th").eq(colIdx).attr("data-field");
                var rowData = $('#grid').data().kendoGrid.dataSource.data()[rowIdx];
                if (columnField == 'Quantity' || columnField == 'PriceBefDi' || columnField == 'DiscPrcnt') {
                    UpdateRow(rowData);
                    UpdateTotal();
                }
            });
        }
        function UpdateTotal() {
            var items = $("#grid").data("kendoGrid").dataSource.data();
            var subTotal = 0, taxAmount = 0;
            for (i = 0; i < items.length; i++) {
                var item = items[i];
                subTotal += item.LineTotal;
                taxAmount += item.VatSum;
            }
            var totalMoney = format2(subTotal, "");
            var total = subTotal + taxAmount;
            $('#subTotal').text(totalMoney);
            $('#taxAmount').text(format2(taxAmount, ""));
            $('#total').text(format2(total, ""));
        }
        function LoadHeader(docHeader) {
            docEntry = docHeader.DocEntry;
            if (docHeader.CANCELED == 'Y') {
                docStatus = "Canceled";
                $('#btnSave').attr('disabled', 'disabled');
                $('#btnSave').addClass("k-button k-state-disabled");
                $('#btnCancel').attr('disabled', 'disabled');
                $('#btnCancel').addClass("k-button k-state-disabled");
                $('#btnCopyTo').attr('disabled', 'disabled');
                $('#btnCopyTo').addClass("k-button k-state-disabled");
            }
            else if (docHeader.DocStatus == 'O') {
                docStatus = "Open";
                $('#btnSave').removeAttr('disabled');
                $('#btnSave').removeClass("k-state-disabled");
                $('#btnCancel').removeAttr('disabled');
                $('#btnCancel').removeClass("k-state-disabled");
                $('#btnCopyTo').removeAttr('disabled');
                $('#btnCopyTo').removeClass("k-state-disabled");
            }
            else if (docHeader.DocStatus == 'C') {
                docStatus = "Closed";
                $('#btnSave').attr('disabled', 'disabled');
                $('#btnSave').addClass("k-button k-state-disabled");
                $('#btnCancel').attr('disabled', 'disabled');
                $('#btnCancel').addClass("k-button k-state-disabled");
                $('#btnCopyTo').attr('disabled', 'disabled');
                $('#btnCopyTo').addClass("k-button k-state-disabled");
            }

            $('#DocEntry').val(docEntry);
            $('#DocStatus').val(docStatus);
            $('#DocStatus').val(docStatus);
            $('#CardCode').val(docHeader.CardCode);
            $('#CardName').val(docHeader.CardName);
            var docDate = docHeader.DocDate;
            var docDateobj = kendo.parseDate(docDate);
            var docDueDate = docHeader.DocDueDate;
            var docDueDateobj = kendo.parseDate(docDueDate);
            var validDate = docHeader.TaxDate;
            var validDateobj = kendo.parseDate(validDate);
            $("#docDate").data("kendoDatePicker").value(null);
            $("#docDate").data("kendoDatePicker").value(docDateobj);
            $("#docDueDate").data("kendoDatePicker").value(null);
            $("#docDueDate").data("kendoDatePicker").value(docDueDateobj);
            $("#taxDate").data("kendoDatePicker").value(null);
            $("#taxDate").data("kendoDatePicker").value(validDateobj);
            $("#Comments").val(docHeader.Comments);
        }
        function GetHeaderByDocEntry() {

            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/GetDocHeaderByDocEntry",
                data: JSON.stringify({
                    docEntry: docEntry
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result.Table) {
                            var docHeader = result.Table;
                            if (docHeader.length > 0) {
                                docHeader = docHeader[0];
                                LoadHeader(docHeader);
                                $("#subTotal").text(format2(docHeader.SubTotal, ""));
                                $("#taxAmount").text(format2(docHeader.VatSum, ""));
                                $("#total").text(format2(docHeader.DocTotal, ""));
                                isUpdate = true;
                            }
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function GetLastRecord() {

            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/GetLastRecord",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != '') {
                        var result = JSON.parse(response.d);
                        if (result.Table) {
                            var docHeader = result.Table;
                            if (docHeader.length > 0) {
                                grid.dataSource.data([]);
                                docHeader = docHeader[0];
                                LoadHeader(docHeader);
                                $("#subTotal").text(format2(docHeader.SubTotal, ""));
                                $("#taxAmount").text(format2(docHeader.VatSum, ""));
                                $("#total").text(format2(docHeader.DocTotal, ""));

                                isUpdate = true;
                                $.ajax({
                                    type: "POST",
                                    url: "SalesQuotation.aspx/ClearSessionData",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    success: function (response) {
                                        grid.dataSource.read();
                                        var url = "SalesQuotation.aspx?DocEntry=" + docEntry + "&IsUpdate=true"
                                        history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);

                                    },
                                    failure: function (response) {
                                    },
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 500) {
                                            alert('Internal error: ' + jqXHR.responseText);
                                        } else {
                                            alert('Unexpected error.' + jqXHR.responseText);
                                        }
                                    }
                                });
                            }
                        }
                    }
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function Cancel() {
            var r = confirm("Do you really want to cancel this document?");
            if (r == true) {
                $.ajax({
                    type: "POST",
                    url: "SalesQuotation.aspx/CancelDoc",
                    data: JSON.stringify({
                        docEntry: docEntry
                    }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data.d != "0") {
                            if ($.isNumeric(data.d)) {
                                isUpdate = 'true';
                                $('#DocEntry').val(data.d);
                                docEntry = $('#DocEntry').val();
                                grid.dataSource.data([]);
                                GetHeaderByDocEntry();
                                $.ajax({
                                    type: "POST",
                                    url: "SalesQuotation.aspx/ClearSessionData",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    success: function (response) {
                                        var url = "SalesQuotation.aspx?DocEntry=" + docEntry + "&IsUpdate=true"
                                        history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);
                                        grid.dataSource.read();
                                    },
                                    failure: function (response) {
                                    },
                                    error: function (jqXHR, textStatus, errorThrown) {
                                        if (jqXHR.status == 500) {
                                            alert('Internal error: ' + jqXHR.responseText);
                                        } else {
                                            alert('Unexpected error.' + jqXHR.responseText);
                                        }
                                    }
                                });
                                setMasterMessage("Operation complete successful!", "success");
                            }
                            else {
                                setMasterMessage(data.d, "error");
                            }
                        }
                        else {
                            setMasterMessage(data.d, "error");
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        if (jqXHR.status == 500) {
                            alert('Internal error: ' + jqXHR.responseText);
                        } else {
                            alert('Unexpected error.' + jqXHR.responseText);
                        }
                    }
                });
            }
        }
        function UpdateProcess() {
            docEntry = $("#DocEntry").val();
            oDocHeader.DocEntry = $("#DocEntry").val();
            oDocHeader.CardCode = $('#CardCode').val();
            oDocHeader.CardName = $('#CardName').val();
            oDocHeader.DocDate = $("#docDate").val();
            oDocHeader.TaxDate = $("#taxDate").val()
            oDocHeader.DocDueDate = $("#docDueDate").val();
            oDocHeader.Comments = $("#Comments").val();

            if (oDocHeader.CardCode == '') {
                setMasterMessage("Please select customer.", "error");
                return;
            }
            if (oDocHeader.DocDate == '') {
                setMasterMessage("Please select Doc Date .", "error");
                return;
            }
            if (oDocHeader.DocDueDate == '') {
                setMasterMessage("Please select Doc Due Date.", "error");
                return;
            }
            if (oDocHeader.TaxDate == '') {
                setMasterMessage("Please select Tax Date.", "error");
                return;
            }
            $.ajax({
                type: "POST",
                url: "SalesQuotation.aspx/UpdateDocToDB",
                data: JSON.stringify({
                    oDocHeader: JSON.stringify(oDocHeader),
                    isUpdate: isUpdate,
                    docEntry: docEntry
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data.d != "0") {
                        if ($.isNumeric(data.d)) {
                            isUpdate = true;
                            $('#DocEntry').val(data.d);
                            docEntry = $('#DocEntry').val();
                            grid.dataSource.data([]);
                            GetHeaderByDocEntry();
                            $.ajax({
                                type: "POST",
                                url: "SalesQuotation.aspx/ClearSessionData",
                                data: '',
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (response) {
                                    var url = "SalesQuotation.aspx?DocEntry=" + docEntry + "&IsUpdate=true"
                                    history.pushState({ docEntry: docEntry, IsUpdate: true }, "Document", url);
                                    grid.dataSource.read();
                                },
                                failure: function (response) {
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    if (jqXHR.status == 500) {
                                        alert('Internal error: ' + jqXHR.responseText);
                                    } else {
                                        alert('Unexpected error.' + jqXHR.responseText);
                                    }
                                }
                            });
                            setMasterMessage("Operation complete successful!", "success");
                        }
                        else {
                            setMasterMessage(data.d, "error");
                        }
                    }
                    else {
                        setMasterMessage(data.d, "error");
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function getPDF() {
            var docEntry = $("#DocEntry").val();
            if (docEntry != '' && docEntry != '0') {
                $.ajax({
                    type: "POST",
                    url: currentPage + "/GetPDF",
                    data: JSON.stringify({
                        docEntry: docEntry
                    }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var html = data.d;
                        var html = data.d;
                        var popupWindow = window.open('', 'Print', 'left=1,top=1,scrollbars=1,toolbar=1,menubar=1');
                        popupWindow.document.write(html);
                        popupWindow.document.close();
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        if (jqXHR.status == 500) {
                            alert('Internal error: ' + jqXHR.responseText);
                        } else {
                            alert('Unexpected error.' + jqXHR.responseText);
                        }
                    }
                });
            }
        }
    </script>
    <table style="width: 100%; border: 1px; height: 120px;">
        <tr>
            <td style="width: 8%;">
                Customer
            </td>
            <td style="width: 25%;">
                <input type="text" class="k-input k-textbox" name="CardCode" id="CardCode" required="required"
                    validationmessage="Pls input Promotion Code." style="width: 290px;" onchange="LoadBP()" />
                <span class="k-icon k-i-search" style="margin-left: 0px; width: 16px; cursor: pointer;"
                    onclick="OpenCustomerList()" title="Choose Customer" id="spanChooseCustomer">
                </span>
            </td>
            <td>
                Posting Date
            </td>
            <td style="width: 330px;">
                <input type="text" name="docDate" id="docDate" required="required" validationmessage="Pls input Promotion Code."
                    style="width: 290px;" />
            </td>
            <td style="width: 120px;">
                Document No.
            </td>
            <td>
                <input type="text" class="k-input k-textbox" name="DocEntry" id="DocEntry" readonly
                    style="width: 290px;" />
            </td>
        </tr>
        <tr>
            <td>
                Customer Name
            </td>
            <td rowspan="2">
                <textarea rows="4" name="CardName" id="CardName" class="k-textbox" style="width: 290px;
                    height: 97%;" readonly> </textarea>
            </td>
            <td>
                Valid Until
            </td>
            <td>
                <input type="text" name="docDueDate" id="docDueDate" required="required" validationmessage="Pls input Promotion Code."
                    style="width: 290px;" />
            </td>
            <td>
                Status
            </td>
            <td>
                <input type="text" class="k-input k-textbox" name="DocStatus" id="DocStatus" style="width: 290px;"
                    readonly />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                Document Date
            </td>
            <td>
                <input type="text" name="taxDate" id="taxDate" required="required" validationmessage="Pls input Document Date"
                    style="width: 290px;" />
            </td>
            <td>
                &nbsp;
            </td>
            <td>
                &nbsp;
            </td>
        </tr>
    </table>
    <br />
    <div id="message" class="demo-section k-header" style="text-align: center">
    </div>
    <div id="customerList">
    </div>
    <div id="salesQuotationList">
    </div>
    <div id="itemList">
    </div>
    <div id="grid">
    </div>
    <br />
    <table style="width: 100%;" border="0">
        <tr>
            <td style="width: 100px;">
                Remarks
            </td>
            <td align="left">
                <textarea rows="2" name="Comments" id="Comments" class="k-textbox" style="width: 60%;
                    height: 70%;"> </textarea>
            </td>
            <td align="right" valign="top">
                <table style="width: 100%; height: 10%;" border="0">
                    <tr>
                        <td class="text-right" style="font-style: italic">
                            Sub Total:
                        </td>
                        <td class="text-right" style="font-weight: bold; color: #0000CC">
                            <span id="subTotal" style="font-weight: bold; color: #0066FF"></span>
                        </td>
                    </tr>
                    <tr>
                        <td class="text-right" style="font-style: italic">
                            Tax Amount:
                        </td>
                        <td class="text-right" style="font-weight: bold; color: #0000CC">
                            <span id="taxAmount" style="font-weight: bold; color: #0066FF"></span>
                        </td>
                    </tr>
                    <tr>
                        <td class="text-right" style="font-style: italic">
                            Grand Total:
                        </td>
                        <td class="text-right" style="font-weight: bold; color: #0000CC">
                            <span id="total" style="font-weight: bold; color: #0066FF"></span>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    <br />
    <table style="margin-top: 0px;" width="100%">
        <tr>
            <td style="width: 60%;">
                <div class="k-edit-buttons k-state-default">
                    <button type="button" id="btnSave" onclick="UpdateProcess();" class="k-button k-button-icontext k-primary"
                        style="width: 150px;">
                        <span class="k-icon k-update"></span>Save</button>
                    <button type="button" id="btnCreateNew" onclick="CreateNew();" class="k-button k-button-icontext k-primary"
                        style="width: 150px;">
                        <span class="k-icon k-i-plus"></span>Create New</button>
                    <button type="button" id="btnCancel" onclick="Cancel();" class="k-button k-button-icontext k-primary"
                        style="width: 150px;">
                        <span class="k-icon k-i-cancel"></span>Cancel</button>
                    <button type="button" id="btnDocumentList" onclick="OpenSQList()" class="k-button k-button-icontext k-primary"
                        style="width: 150px;">
                        <span class="k-icon k-i-hbars"></span>SQ List</button>
                    <button type="button" id="btnLastRecord" onclick="GetLastRecord()" class="k-button k-button-icontext k-primary"
                        style="width: 150px;">
                        <span class="k-icon k-i-seek-e"></span>Last Record</button>
                </div>
            </td>
            <td align="right">
              <button type="button" id="exportPDF" onclick="getPDF()" class="k-button k-button-icontext k-primary"
                    style="width: 160px;">
                    <span class="k-icon k-i-pdf"></span>Export To PDF</button>
                <button type="button" id="btnCopyTo" onclick="CopyToSO()" class="k-button k-button-icontext k-primary"
                    style="width: 150px;">
                    <span class="k-icon k-i-rotatecw"></span>Copy to SO</button>
            </td>
        </tr>
    </table>
</asp:Content>
